<?php
/*
 * 
 *  AJAX
 * 
 * */
require_once 'Zend/oss/sdk.class.php';
class AjaxController extends Zend_Controller_Action
{

    public function init()
    {
        
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('getmodel', 'json')
                    ->addActionContext('getcity', 'json')
                    ->addActionContext('upload', 'json')
                    ->initContext();
                    
    }

    
    public function getmodelAction() {
        
        $brand_id = intval($this->_request->getParam('b_id'));
        
        $carmodel = new Model_CarModel();
        $data = $carmodel->getModel($brand_id);
        
        foreach ($data as $company){
            echo "<optgroup label=\"-- $company[company] --\"></optgroup>";
            foreach ($company[model] as $model){
                echo "<option value=\"$model[id]\">$model[model]</option>";
            }
        }

        //echo json_encode($data);
        exit();
        
    }
    
    //CARNAME
    public function getcarnameAction(){
        $model_id = intval($this->_request->getParam('m_id'));
        
        $carmodel = new Model_CarModel();
        $data = $carmodel->getCarname($model_id);
        
        if (empty($data)){
            echo "<option value=\"-1\">其他车型</option>";
        }else{
            foreach ($data as $name){
            	echo "<option value=\"$name[id]\">$name[name]</option>";
            }
        }


        	//echo json_encode($data);
        exit();
    }
    
    //通过省 取城市名  子级名称 无下限
    public function getcityAction() {
        
        $id = intval($this->_request->getParam('id'));
        $city_arr = new Model_City();
        $data = $city_arr->getCityChild($id);
        
        
        
        foreach ($data as $value){
            echo "<option value=\"$value[id]\">$value[name]</option>";
        }
        exit();
    }
    
    //取号码
    public function getmoblieAction() {
    	
        $cid = intval($this->_request->getParam('cid'));
        $sale = new Model_CarSale();
        
        $data = $sale->getViewName($cid);
        
        echo $data[0][contact_tel];
        exit();
    }
    
    //城市分站
    public function getallcityAction() {
        $city_arr = new Model_City();
        
        foreach ($city_arr->getAllCity() as $value){
            echo "<li><a href=\"/buy/index/city_id/$value[id]\">$value[name]</a></li>";
        }

        exit();
    }
    
    //取配置 19行
    public function getdetailAction() {
        $name_id = intval($this->_request->getParam('name_id'));
        $detail = new Model_CarDetailtb();

        $data = $detail->getAlldetail($name_id);
        
    	foreach ($data as $k=>$value){
    	    echo "<tr><td>$value[deploy]</td><td>$value[deploy_value]</td></tr>";
    	    if ($k >= 19){
    	        break;
    	    }
    	}
   
    	exit();
    }
    
    //保存至桌面
    public function savedesktopAction() {
        
        $cid = intval($this->_request->getParam('cid'));
        $title = $this->_request->getParam('title', '车源信息');
        
        if ($cid){
           
            $Shortcut = "[DEFAULT]
                    BASEURL=http://www.taochele.com/
                    [InternetShortcut]
                    URL=http://www.taochele.com/buy/view/cid/$cid
                    Modified=B07A55D9386FCA01CA
                    IconFile=http://www.taochele.com/img/favicon.ico
                    IconIndex=1";

            $ua = $_SERVER["HTTP_USER_AGENT"];
                    $filename = $title." - 淘车乐".".url";
                    $encoded_filename = urlencode($filename);
                    $encoded_filename = str_replace("+", "%20", $encoded_filename);
                    header('Content-Type: application/octet-stream');
            if(preg_match("/MSIE/", $ua)){
                header('Content-Disposition: attachment; filename="'.$encoded_filename.'"');
            }else if(preg_match("/Firefox/", $ua)){
                header('Content-Disposition: attachment; filename*="utf8\'\''.$filename.'"');
            }else{
                header('Content-Disposition: attachment; filename="'.$filename.'"');
            }

            
            echo $Shortcut;
        }

        
        //return $Shortcut;
        exit();
    }
    
    
    //AJAX 获取验证码
    public function getcaptchaAction() {
        
        $core = new Model_Core();
        $res = $core->getCaptcha();
        echo $res;
        exit();
    }

    //用户名合法性检查
    public function getusernamecheckAction(){
        $core = new Model_Core();
        
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkUsername($value);
        echo $res;
        exit();
    }
    
    //密码合法性
    public function getpasswordcheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkPassword($value);
    
        echo $res;
        exit();
    }
    //邮箱合法性
    public function getemailcheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkEmail($value);
    
        echo $res;
        exit();
    }
    
    //验证码 校验
    public function getcaptchacheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkCaptcha($value);
    
        echo $res;
        exit();
    }
    
    //公司名称
    public function getconamecheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkConame($value);
    
        echo $res;
        exit();
    }
    
    //公司地址
    public function getaddresscheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));

        $res = $core->checkCoaddress($value);

    
        echo $res;
        exit();
    }
    
    //真实姓名
    public function getrealnamecheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkRealname($value);
    
        echo $res;
        exit();
    }
    
    //身份证号
    public function getidnocheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkIdcard($value);
    
        echo $res;
        exit();
    }
    
    //手机号
    public function getphonecheckAction(){
        $core = new Model_Core();
    
        $value = trim($this->_request->getParam('value'));
        $res = $core->checkPhone($value);
        
    
        echo $res;
        exit();
    }
    
    //登陆 用户名 校验
    public function getloginaccountcheckAction(){
    	$core = new Model_Core();
    
    	$value = trim($this->_request->getParam('value'));
    	$res = $core->checkLoginAccount($value);
    	//$login_num = $core->protectLogin($username);
    
    	echo $res;
    	exit();
    }
    
    //输入用户后 检查COOKIE 是否需要验证码
    public function isprotectloginAction() {
        $core = new Model_Core();
        $value = trim($this->_request->getParam('value'));
        $core->protectLogin($value);
        exit();
    }
    
    //登陆密码验证
    public function getlogincheckAction(){
    	$core = new Model_Core();
    
    	$username = trim($this->_request->getParam('username'));
    	$password = md5($this->_request->getParam('password'));
    	$res = $core->checkLoginPw($username, $password);
    	echo $res;
    	exit();
    }
    
    
    //登陆提交 表单
    public function dologinAction() {
        
        $core = new Model_Core();
        $username = trim($this->_request->getParam('username'));
        $password = md5($this->_request->getParam('password'));
        $captcha = trim($this->_request->getParam('captcha'));
        $autologin = $this->_request->getParam('autologin');
        $ref = trim($this->_request->getParam('ref'));
        
        $data = array(
            'username' => $username,
            'password' => $password,
            'captcha'  => $captcha,
        );
        
        $islogin = $core->checkLogin($data);
        if ($islogin == ""){
            $member = new Model_CommonMembers();
            $member_res = $member->getUserByAccount($username);
            
            //LASTLOGIN
            $member->setLastLogin($member_res[uid], $_SERVER['REMOTE_ADDR']);
            
            if ($autologin == 1){
                $core->setLogin($member_res[uid], 604800);//一周有效
            }else{
                $core->setLogin($member_res[uid]);//即时
            }
            if ($ref == ""){
                $ref = "/set";
            }
                        
            echo "<script type=\"text/javascript\">successMsg(\"登陆成功,正在跳转...\", \"$ref\");</script>";
        }else{
            echo "<script type=\"text/javascript\">errorMsg(\"$islogin\");</script>";
        }
        exit();
    }
    
    
    //找回密码 提交
    public function doforgotAction() {
        $core = new Model_Core();
        $step = intval($this->_request->getParam('step'));
        $account = trim($this->_request->getParam('account'));
        $email = trim($this->_request->getParam('email'));
        $answer = trim($this->_request->getParam('answer'));
        $captcha = trim($this->_request->getParam('captcha'));
        $mode = intval($this->_request->getParam('mode'));
        
        $result = 1;
        $tcl_session = new Zend_Session_Namespace('taochele');
        if ($step == 1) {
            $result = $core->checkLoginAccount($account);
            if ($result == 1){
                $tcl_session->forgotAccount = $account;
            }

        }
        if ($step == 2){
            
            $forgotAccount = $tcl_session->forgotAccount;
            
            if (!$forgotAccount){
                echo "<script>window.open(\"/member/forgot/step/0\", \"_self\");</script>";
                exit();
            }
            if ($core->checkCaptcha($captcha) != 1){
                $result = $core->checkCaptcha($captcha);
            }else{
                $members = new Model_CommonMembers();
                $m_res = $members->getUserByAccount($forgotAccount);
                
                if ($mode == 1){
                    if ($m_res[answer] != $answer){
                        $result = "安全回答不正确";
                    }else{
                        $tcl_session->forgotAuth = "1";
                        echo "<script>window.open(\"/member/forgot/step/2\", \"_self\");</script>";
                        exit();
                    }
                }elseif ($mode == 2){
                    if ($m_res[email] != $email){
                        $result = "请输入正确的邮箱账号";
                    }else{
                        $mailurl = explode('@', $email);
                        $mailurl = $mailurl[1];
                        $now = date("Y-m-d H:i:s", time());
                        
                        //SALT 发送时间 入库
                        $salt = sha1(dechex(rand(99,9999)));
                        $members->setForgotSalt($m_res[uid], $salt);
                        $content = "
                                                                           该邮件为淘车乐(www.taochele.com) 会员密码找回专用邮件, 如果您没有申请密码找回服务, 请直接忽略本邮件, 如果您主动忽略本邮件我们不会修改您的密码及其他信息。<br/>
                        	尊敬的 $m_res[username], 您已在 $now 进行了密码重置的操作, 请点击以下链接(如果无法点击请完整复制该链接到您的浏览器中打开):<br/>
                        	http://www.taochele.com/member/forgot/step/2/uid/$m_res[uid]/salt/$salt 
                        	<br/>
                        	点击链接进行您的密码重置操作！为了保证您的账户安全, 该链接仅一次有效, 请在2小时内完成操作！
                        	<br/><br/><br/>
                        	本邮件为系统自动发出请匆回复<br/>
                        	www.taochele.com<br/>
                        	淘车乐会员中心 <br/>
                        ";
                        $ismail = $core->sendMail($m_res[username], $email, "$m_res[username] —— 淘车乐用户账号密码找回专用邮件", $content, "淘车乐用户中心");
                        
                        $msg = "系统已发送重置密码邮件至您的邮箱 $email,请在2小时内完成密码修改。\n<a href='http://mail.$mailurl' target='_blank'>点击此处登陆邮箱查看邮件</a>\n&nbsp;&nbsp;如果您长时间没有收到邮件,请检查您的垃圾信箱并将我们加入白名单！";
                        if ($ismail == true){
                            $result = $msg;
                        }else{
                            //错误报告给管理员
                            $result = "系统内部错误, 请稍后重试!";//$ismail; //
                        }
                        //exit();
                    }
                }else{
                    $result = "内部错误, 请刷新后重试";
                }

            }

        }

        echo $result;
        exit();
    }
    
    public function setnewpwAction() {
        
        $password = trim($this->_request->getParam('password'));
        $passwordagain = trim($this->_request->getParam('passwordagain'));
        $tcl_session = new Zend_Session_Namespace('taochele');
        $account = $tcl_session->forgotAccount;
        $auth = $tcl_session->forgotAuth;
        
        $core = new Model_Core();
        $is_pw = $core->checkPassword($password);
        if ($is_pw == 1){
            if ($password == $passwordagain){
            	if ($account && $auth){
            		$member = new Model_CommonMembers();
            		$m_res = $member->getUserByAccount($account);
            		$member->setNewPassword($m_res[uid], md5($password));
            		echo "<script>successMsg('操作成功, 正在跳转...', '/set')</script>";
            	}else{
            		echo "<script>errorMsg('来源地址不正确, 请重试')</script>";
            	}
            }else{
            	echo "<script>errorMsg('两次输入的密码不一致')</script>";
            }
        }else{
            echo "<script>errorMsg('".$is_pw."')</script>";
        }

        
        exit();
    }

    
    public function updatepicnumAction(){
        
        $session_id = trim($this->_request->getParam('session_id'));
        $num = intval($this->_request->getParam('num'));
        $tcl_session = new Zend_Session_Namespace('taochele_'.$session_id);

        $tcl_session->upload_num = $num;
        
        exit();
    }
    
    
    //上传车源图片
    public function uploadAction() {
    
        $core = new Model_Core();
        
        $session_id = trim($this->_request->getParam('session_id'));
        $tcl_session = new Zend_Session_Namespace('taochele_'.$session_id);
        $upload_num = $tcl_session->upload_num;
        $upload_num++;
        $tcl_session->upload_num = $upload_num;
        
        
        // Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
        $POST_MAX_SIZE = ini_get('post_max_size');
        $unit = strtoupper(substr($POST_MAX_SIZE, -1));
        $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
        
        if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
            header("HTTP/1.1 500 Internal Server Error"); // This will trigger an uploadError event in SWFUpload
            echo "POST exceeded maximum allowed size.";
            exit(0);
        }
        
        // Settings
        $save_path = getcwd()."/uploads/img/".date(Y)."/".date(m)."/".date(d)."/".$session_id;				// The path were we will save the file (getcwd() may not be reliable and should be tested in your environment)
        $oss_path = date(Y)."/".date(m)."/".date(d)."/".$session_id;
        $core->creatdir($save_path);
        
        //$save_url = "/uploads/img/".date(Y)."/".date(m)."/".date(d)."/".$session_id;	
        $save_url = "http://img.taochele.com/".date(Y)."/".date(m)."/".date(d)."/".$session_id;	
        
        
        $upload_name = "Filedata";
        $max_file_size_in_bytes = "20971520";				// 20MB in bytes
        $extension_whitelist = array("jpg", "jpeg", "png");	// Allowed file extensions
        $valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';				// Characters allowed in the file name (in a Regular Expression format)
        
        // Other variables
        $MAX_FILENAME_LENGTH = 260;
        $file_name = "";
        $file_extension = "";
        $uploadErrors = array(
                0=>"There is no error, the file uploaded with success",
                1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
                2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
                3=>"The uploaded file was only partially uploaded",
                4=>"No file was uploaded",
                6=>"Missing a temporary folder"
        );
        
        
        // Validate the upload
        if (!isset($_FILES[$upload_name])) {
            $this->HandleError("No upload found in \$_FILES for " . $upload_name);
            exit(0);
        } else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
            $this->HandleError($uploadErrors[$_FILES[$upload_name]["error"]]);
            exit(0);
        } else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
            $this->HandleError("Upload failed is_uploaded_file test.");
            exit(0);
        } else if (!isset($_FILES[$upload_name]['name'])) {
            $this->HandleError("File has no name.");
            exit(0);
        }
        
        // Validate the file size (Warning: the largest files supported by this code is 2GB)
        $file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
        if (!$file_size || $file_size > $max_file_size_in_bytes) {
            $this->HandleError("File exceeds the maximum allowed size");
            exit(0);
        }
        
        if ($file_size <= 0) {
            $this->HandleError("File size outside allowed lower bound");
            exit(0);
        }
        
        $sh = end(explode(".", $_FILES[$upload_name]['name']));
        // Validate file name (for our purposes we'll just remove invalid characters)
        $file_name = "/".$session_id.$upload_num.".".$sh;
        
        if (strlen($file_name) == 0 || strlen($file_name) > $MAX_FILENAME_LENGTH) {
            $this->HandleError("Invalid file name");
            exit(0);
        }
        
        
        // Validate that we won't over-write an existing file
        if (file_exists($save_path . $file_name)) {
            $this->HandleError("File with this name already exists");
            exit(0);
        }
        
        // Validate file extension
        $path_info = pathinfo($_FILES[$upload_name]['name']);
        $file_extension = $path_info["extension"];
        $is_valid_extension = false;
        foreach ($extension_whitelist as $extension) {
            if (strcasecmp($file_extension, $extension) == 0) {
                $is_valid_extension = true;
                break;
            }
        }
        if (!$is_valid_extension) {
            $this->HandleError("Invalid file extension");
            exit(0);
        }
        
        
        if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
            $this->HandleError("File could not be saved.");
            exit(0);
        }
        $file = $_FILES[$upload_name]["tmp_name"];
        
        //图片数组 SESSION
        //$core->setPicSession($session_id, $upload_num, $file_name);
        //setcookie("pic_arr", "3333");
        //print_r($pic_arr);
        
        $small_file = "/".$session_id.$upload_num."_small".".".$sh;
        $big_file = "/".$session_id.$upload_num."_big".".".$sh;
        $huge_file = "/".$session_id.$upload_num."_huge".".".$sh;
        
        //切  大 中 小 三个大小图片
        //SMALL
        $core->cutphoto($save_path.$file_name,$save_path.$small_file,120,90);
        //BIG
        $core->cutphoto($save_path.$file_name,$save_path.$big_file,400,300);
        //HUGE
        $core->cutphoto($save_path.$file_name,$save_path.$huge_file,640,480);
        
        $waterImage = getcwd()."/img/watermark.png";
        @$core->imageWaterMark($save_path.$big_file,9,$waterImage);//图片加水印
        @$core->imageWaterMark($save_path.$huge_file,9,$waterImage);//图片加水印
        //清理原图
        //@unlink($save_path.$file_name);
        //计划任务清理全部
        
        //OSS 上传
        $oss_sdk_service = new ALIOSS();
        //设置是否打开curl调试模式
        $oss_sdk_service->set_debug_mode(FALSE);
        //BUCKET NAME
        $bucket = "taochele";
        $oss_sdk_service->create_object_dir($bucket, $oss_path);
        //SMALL
        $response = $oss_sdk_service->upload_file_by_file($bucket, $oss_path.$small_file, $save_path.$small_file);
        //BIG
        $response = $oss_sdk_service->upload_file_by_file($bucket, $oss_path.$big_file, $save_path.$big_file);
        //HUGE
        $response = $oss_sdk_service->upload_file_by_file($bucket, $oss_path.$huge_file, $save_path.$huge_file);

        
        echo  "<img src=\"$save_url$small_file\"><input type='hidden' name='pic_arr[]' value=\"$upload_num.$sh\" />";
        exit();
    }
    
    /* Handles the error output. This error message will be sent to the uploadSuccess event handler.  The event handler
     will have to check for any error messages and react as needed. */
    protected function HandleError($message) {
        echo $message;
    }
    
    
    
    //停用     删除图片 SESSION
    public function removeimgAction(){
        $session_id = trim($this->_request->getParam('session_id'));
        $id = trim($this->_request->getParam('id'));
        
        $tcl_session = new Zend_Session_Namespace('taochele_'.$session_id);
        $pic_arr = $tcl_session->pic_arr;

        unset($pic_arr[$id]);
        $tcl_session->pic_arr = $pic_arr;
        
        //print_r($pic_arr);
        
        exit();
    }
    
    //删除车源信息
    public function saledelAction() {
    	
        $ids = trim($this->_request->getParam('ids'));        
        $core = new Model_Core();
        $user = $core->isLogin();
        
        
        $sale = new Model_CarSale();
        $res = $sale->setSaleDel($ids, $user[uid]);
        
        if ($core->isValidFloat($res)){
            echo "1";
        }else{
            echo $res;
        }
        exit();
    }
    
    
    //售出车源信息
    public function salesaleAction() {
    	 
    	$ids = trim($this->_request->getParam('ids'));
    	$core = new Model_Core();
    	$user = $core->isLogin();
    
    
    	$sale = new Model_CarSale();
    	$res = $sale->setSaleSale($ids, $user[uid]);
    
    	if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
    	exit();
    }
    
    //恢复显示车源信息
    public function restoreAction() {
    
    	$id = trim($this->_request->getParam('id'));
    	$core = new Model_Core();
    	$user = $core->isLogin();
    
    
    	$sale = new Model_CarSale();
    	$res = $sale->setRestore($id, $user[uid]);
    
    	if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
    	exit();
    }
    
    //刷新车源信息
    public function refreshAction() {
    
    	$id = trim($this->_request->getParam('id'));
    	$core = new Model_Core();
    	$user = $core->isLogin();
    
    	$m_status = new Model_CommonMembersStatus();
    	
    	$m_res = $m_status->isRefresh($user[uid]);
    	
		if ($m_res == false){
		    echo "您已超过每天刷新次数上限(免费用户为5条)!您可以通过<a href='/set/profit/ac/refresh'>推广中心</a>购买更多刷新次数！";
		    exit();
		}
    
    	$sale = new Model_CarSale();
    	$res = $sale->setRefresh($id, $user[uid]);
    
    	if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
    	exit();
    }
    
    //删除收藏
    public function favoritesdelAction() {
    
    	$ids = trim($this->_request->getParam('ids'));
    	$core = new Model_Core();
    	$user = $core->isLogin();
    	
    	$ids = explode(',', $ids);

    	$fav = new Model_CommonFavorites();
    	$res = $fav->setFavoritesDel($ids, $user[uid]);
    
    	if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
    	exit();
    }
    
    //收藏
    public function addfavoriteAction() {
        
        $ids = trim($this->_request->getParam('ids'));
        $core = new Model_Core();
        $user = $core->isLogin();
        
        
        $fav = new Model_CommonFavorites();
        
        $res = $fav->setFavorite($ids, $user[uid]);
        
        
        
        if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
        exit();
    }
    
    
    //显示消息详细 
    public function showmsgAction() {
    	
        $id = intval($this->_request->getParam('id'));
        $msg = new Model_CommonMsg();
        $content = $msg->getMsgContent($id);
        $msg->setMsgIsread($id);
        
        echo $content[content];
        
        exit();
    }
    
    //标记已读
    public function msgisreadAction() {
    	
        $ids = trim($this->_request->getParam('ids'));
        $core = new Model_Core();
        $msg = new Model_CommonMsg();
        
        $res = $msg->setMsgIsread($ids);
        if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
        exit();
    }
    
    
    //删除消息
    public function msgdelAction() {
    
    	$ids = trim($this->_request->getParam('ids'));
    	$core = new Model_Core();
    	$user = $core->isLogin();
    	 
    	$ids = explode(',', $ids);
    
    	$msg = new Model_CommonMsg();
    	$res = $msg->setMsgDel($ids, $user[uid]);
    
    	if ($core->isValidFloat($res)){
    		echo "1";
    	}else{
    		echo $res;
    	}
    	exit();
    }

    //审核消息
    public function auditAction() {
    
    	$ids = trim($this->_request->getParam('ids'));
    	$core = new Model_Core();
    	$admin = $core->isLogin();
    	
    	if ($admin[groupid] == 1){    	    
    	    $sale = new Model_CarSale();
    	    $res = $sale->setSaleAudit($ids);
    	    
    	    if ($core->isValidFloat($res)){
    	    	echo "1";
    	    }else{
    	    	echo $res;
    	    }
    	}

    	exit();
    }
    
    //账号管理   个人资料 
    public function setprofileAction() {
        
        $app = intval($this->_request->getParam('app'));
        $core = new Model_Core();
        if ($app == 1){
            $realname = trim($this->_request->getParam('realname'));
            $gender = intval($this->_request->getParam('gender'));
            $idno = trim($this->_request->getParam('idno'));
            $flag = 0;
            if ($core->CheckChinese($realname)){
                $err_msg = "真实姓名必须为中文";
                $flag = 1;
            }
            if ($core->CheckChineseLen($realname) > 5){
                $err_msg = "真实姓名最长5个中文字符";
                $flag = 1;
            }
            if (!$core->isIdno($idno) && $idno){
                $err_msg = "身份证号码格式错误";
                $flag = 1;
            }
            
            if ($flag == 1){
                echo "<script>alert('".$err_msg."')</script>";
                exit();
            }
            $data = array(
                    'realname'    => $realname,
                    'gender'      => $gender,
                    'idno'        => $idno,
            );
            $profile = new Model_CommonMembersProfile();
            $res = $profile->setProfile($data);
        }
        
        if ($app == 2){
            
            $setphone = trim($this->_request->getParam('setphone'));
            $setemail = trim($this->_request->getParam('setemail'));
            $question = intval($this->_request->getParam('question'));
            $answer = trim($this->_request->getParam('answer'));
            $setpassword = trim($this->_request->getParam('setpassword'));
            $setnew_password = trim($this->_request->getParam('setnew_password'));
            $setnew_password_again = trim($this->_request->getParam('setnew_password_again'));
            $captcha = trim($this->_request->getParam('captcha'));
            
            $flag = 0;
            $member = $core->isLogin();
            $data = array();
            //手机
            if ($setphone != $member[phone]){
                if ($core->checkPhone($setphone) != 1){
                    $err_msg = $core->checkPhone($setphone);
                    $flag = 1;
                }
            }
            //邮箱
            if ($setemail != $member[email]){
                if ($core->checkEmail($setemail) != 1){
                    $err_msg = $core->checkEmail($setemail);
                    $flag = 1;
                }
            }
            $data = array(
            		'email'        => $setemail,
            		'phone'        => $setphone,
            );
            //安全问题

                if ($question == 0){
                    $data[question] = 0;
                    $data[answer] = "";
                }else{
                    $data[question] = $question;
                    $data[answer] = $answer;
                }

            if ($setnew_password_again != $setnew_password){
                $err_msg = "两次输入的新密码不一致";
                $flag = 1;
            }
            if ($setnew_password){
                if ($core->checkPassword($setnew_password) != 1){
                	$err_msg = $core->checkPassword($setnew_password);
                	$flag = 1;
                }else{
                    $data[password] = md5($setnew_password);
                }
                
            }

            
            if ($core->checkLoginPw($member[username], md5($setpassword)) != 1){
                $err_msg = "原密码错误, ".$core->checkLoginPw($member[username], md5($setpassword));
                $flag = 1;
            }

            if ($core->checkCaptcha($captcha) != 1){
                $err_msg = $core->checkCaptcha($captcha);
                $flag = 1;
            }
            if ($flag == 1){
                echo "<script>alert('".$err_msg."')</script>";
                exit();
            }
            

            $memberdb = new Model_CommonMembers();
            $res = $memberdb->setMemberProfile($data);
        }


        echo "<script>alert('修改成功！')</script>";

        
        exit();
    }
    
    //右侧 PROFIT 根据屏幕高度调整输出数
    public function getrprofitAction() {
        $count = intval($this->_request->getParam('count'));
        $city_id = intval($this->_request->getParam('city_id'));
        
        $sale = new Model_CarSale();
        $res = $sale->getProfitCars($city_id, "", $count);
    	
        $core = new Model_Core();
        
        foreach ($res as $k=>$value){
            echo "<li>";
            echo "<a href=\"/buy/view/cid/$value[id]\" class=\"thumbnail\" target=\"_blank\" title=\"$value[title]\">";
            echo "<img src=".$value[img_dir].$value[session_id].'/'.$value[session_id].str_replace('.', '_small.', $value[car_img])." width=\"120\" />";
            echo "<p>".$core->cutstr($value[title], 30)."</p>";
            echo "</a>";
            echo "</li>";
        }
        
        exit();
    }
    
    //COOKIE 浏览记录
    public function gethistoryAction() {
    	$count = intval($this->_request->getParam('count'));
    	
    	$history = unserialize(stripslashes($_COOKIE['buy_history']));
    	
    	if ($history){
    	    
    	    //echo $history;
    	    $i=0;
    	    foreach (array_reverse($history) as $k=>$value){
    	    	echo $value;
    	    	if ($i > $count){
    	    	    break;
    	    	}
    	    	$i++;
    	    }
    	}else{
    	    echo "<small>您的浏览记录空空如也</small>";
    	}
    	

    	
    	exit();
    }
    
    
    //浏览记录 AJAX写入
    public function sethistoryAction() {
        $cid = intval($this->_request->getParam('cid'));
        $title = trim($this->_request->getParam('title'));
        
        $history = unserialize(stripslashes($_COOKIE['buy_history']));


        /*
        $data = array(
        	'cid' => $cid,
        	'title' => $title,
        );*/
		$data = "<li><a href=\"/buy/view/cid/$cid\" target=\"_blank\">$title</a></li>";

		    if ($data){
		        $history[$cid] = $data;
		    }

		        
        setcookie("buy_history", serialize($history), time() + 604800, '/');
        
        exit();
    }

	//清除 浏览记录
	public function clearhistoryAction() {
		
	    setcookie("buy_history", "", 0, '/');
	    exit();
	}
	
	//浏览数记录
	public function setviewsAction() {
	    $cid = intval($this->_request->getParam('cid'));
	    
	    $is_view = $_COOKIE['view_'.$cid];
	    
	    //COOKIE 防刷, 减SQL压力
	    if (!$is_view){
	        $sale = new Model_CarSale();
	        $sale->setViews($cid);
	    }

	    
	    setcookie('view_'.$cid, "1", time() + 900);
	    
	    exit();
	}
    
	//BAN USER
	public function banAction() {
		
	    $uid = intval($this->_request->getParam('uid'));
	    $members = new Model_CommonMembers();
	    $id = $members->setBan($uid);
	    
	    echo $id;
	    exit();
	}
	
	//REBAN
	public function rebanAction() {
	
		$uid = intval($this->_request->getParam('uid'));
		$members = new Model_CommonMembers();
		$id = $members->setReBan($uid);
		 
		echo $id;
		exit();
	}
	
	
	//管理员 修改用户
	public function setedituserAction() {
		
	    $uid = intval($this->_request->getParam('uid'));
	    $groupid = intval($this->_request->getParam('groupid'));
	    $setphone = trim($this->_request->getParam('setphone', ""));
	    $setemail = trim($this->_request->getParam('setemail', ""));

	    $setpassword = trim($this->_request->getParam('setpassword'));

	    $flag = 0;
	    $core = new Model_Core();
	    $memberdb = new Model_CommonMembers();
	    $member = $memberdb->getByUid($uid);
	    $data = array();
	    //手机
	    if ($setphone && $setphone != $member[phone]){
	    	if ($core->checkPhone($setphone) != 1){
	    		$err_msg = $core->checkPhone($setphone);
	    		$flag = 1;
	    	}
	    }
	    //邮箱
	    if ($setemail && $setemail != $member[email]){
	    	if ($core->checkEmail($setemail) != 1){
	    		$err_msg = $core->checkEmail($setemail);
	    		$flag = 1;
	    	}
	    }
	    
	    
	    $data = array(
	    		'email'        => $setemail,
	    		'phone'        => $setphone,
	    		'groupid'	   => $groupid,
	    );
	    

	    if ($setpassword){
	    	if ($core->checkPassword($setpassword) != 1){
	    		$err_msg = $core->checkPassword($setpassword);
	    		$flag = 1;
	    	}else{
	    		$data[password] = md5($setpassword);
	    	}
	    
	    }
	    
	    if ($flag == 1){
	    	echo "<script>alert('".$err_msg."')</script>";
	    	exit();
	    }
	    
	    
	    //检查登陆是否为管理员
	    $admin = $core->isLogin();
	    
	    if ($admin[groupid] == 1){
	    
	    	$res = $memberdb->setMemberProfile($data);
	    }
	    
	    echo "<script>alert('修改成功！')</script>";
	    exit();
	}
	
	//处理举报
	public function dojubaoAction() {
		
	    echo "<script>alert('修改成功！')</script>";
	    exit();
	}
	
	
}

